<?php
namespace  app\middleware;
use think\facade\Config;
use think\Request;

// 接口速率中间件

class  ApiRateMiddleware{

    /**
     * 处理请求
     *
     * @param Request $request
     * @param Closure $next
     * @return Response
     */
    public function handle(Request $request,\Closure $next){
        //从redis接口中获取数据


         $uid=$request->post('uid');
        $rateLimit=Config::get('rate.rateLimit');

        $redisLink=linkRedis(11);
        $url=$request->url();
        $requestUtl=$url."_".$uid;
         if ($rateLimit>0){
            $count = $redisLink->get($requestUtl);
             if ($count){
                if ($count >$rateLimit){
                    $redisLink->del($requestUtl);
                    returnFail(24001,'请求速率太快了,请慢一点');
                }else{
                    $redisLink->incr($requestUtl);
                }
            }else{
                 //1分钟60次
                $redisLink->set($requestUtl,1,60);
            }
        }
        return $next($request);
    }
}